package com.haighcom.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.haighcom.common.RedisConstant;
import com.haighcom.config.RedisConfig;
import com.haighcom.entity.PageResult;
import com.haighcom.entity.QueryPageBean;
import com.haighcom.mapper.TSetmealCheckgroupMapper;
import com.haighcom.mapper.TSetmealMapper;
import com.haighcom.model.Setmeal;
import com.haighcom.model.TSetmeal;
import com.haighcom.model.TSetmealCheckgroupKey;
import com.haighcom.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.JedisPool;

import javax.annotation.PostConstruct;

@Service
public class SetmealServiceImpl implements SetmealService {


    private static JedisPool jedisPool;
    @Autowired
    private RedisConfig redisConfig;

    @PostConstruct
    public void init(){
        jedisPool = redisConfig.redisPoolFactory();
    }

    @Autowired
    private TSetmealMapper tSetmealMapper;

    @Autowired
    private TSetmealCheckgroupMapper tSetmealCheckgroupMapper;



    @Override
    public void add(TSetmeal tSetmeal, Integer[] checkgroupIds) {
        tSetmealMapper.insertSelective(tSetmeal);
        String img = tSetmeal.getImg();
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,img);
        Integer id = tSetmeal.getId();

        for (Integer checkgroupId : checkgroupIds) {
            TSetmealCheckgroupKey tSetmealCheckgroupKey = new TSetmealCheckgroupKey();
            tSetmealCheckgroupKey.setSetmealId(id);
            tSetmealCheckgroupKey.setCheckgroupId(checkgroupId);
            tSetmealCheckgroupMapper.insertSelective(tSetmealCheckgroupKey);
        }

    }

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        PageHelper.startPage(currentPage,pageSize);
        Page<Setmeal> pages = tSetmealMapper.findPage(queryString);
        return new PageResult(pages.getTotal(),pages.getResult());
    }
}
